import React, {useRef, useState} from "react";
import { View, Button, Input } from "@tarojs/components";
import ChildCom from "./child"
import { refType } from "@/types"
import {ShowToast} from "@/utils";
import "./index.scss"

const RefPage: React.FC = () => {

  const [str, setStr] = useState('')
  const refObj = useRef<refType>({
    valPlus: () => {}
  })
  const iptRef = useRef<HTMLInputElement>(null)
  const getFocus = () => {
    iptRef.current?.focus()
  }
  const getInputValue = () => {
    ShowToast(`输入值：${iptRef.current?.value}`)
  }
  const showRef = () => {
    console.log(refObj.current)
  }
  const inputChange = (e) => {
    setStr(e.target.value)
  }
  const valPlus = () => {
    if (refObj && refObj.current) {
      refObj.current.valPlus()
    }
  }

  const showChildVal = (refVal) => {
    console.log(refVal);
  }

  return(
    <View className="page safe-page flex-column">
      <View className="row">ref演示</View>
      <View className="row">------------原生组件----------</View>
      <View className="row">输入值：{str}</View>
      <View className="flex-row flex-warp">
        <Button className="btn" size="mini" onClick={getFocus}>获取input焦点</Button>
        <Button className="btn" size="mini" onClick={getInputValue}>获取input输入值</Button>
        <View className="flex1"></View>
      </View>
      <Input className="input row" type="text" ref={iptRef} onInput={inputChange} />
      <View className="row">------------自定义hook组件----------</View>
      <View>
        <Button className="btn" size="mini" onClick={showRef}>打印ref传值</Button>
        <Button className="btn" size="mini" onClick={valPlus}>调用ref方法</Button>
      </View>
      <View className="row">
        <ChildCom showProps={showChildVal} ref={refObj}></ChildCom>
      </View>
    </View>
  )
}

export default RefPage
